package cn.edu.hit.ajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;

import cn.edu.hit.db.DBTools;
import com.opensymphony.xwork2.ActionSupport;

public class AjaxAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private HttpServletResponse response = ServletActionContext.getResponse();
	private HttpServletRequest request = ServletActionContext.getRequest();
	private HttpSession session = request.getSession();

	/** 
	 * 验证注册信息是否合法
	 * 
	 * @return
	 */
	public String checkRegister() {
		try {
			response.setContentType("text/plain");
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			String parameter = request.getParameter("type");
			if (parameter.equals("checkNumber")) {
				String number = request.getParameter("number");
				String sql = "select student_number from student where student_number=?";
				PreparedStatement ps = DBTools.getConnection()
						.prepareStatement(sql);
				ps.setString(1, number);
				ResultSet rs = ps.executeQuery();
				if (rs.next()) {
					out.print("yes");
				} else {
					out.print("no");
				}
				out.flush();
				out.close();
				rs.close();
			} else if (parameter.equals("checkName")) {
				String number = request.getParameter("number");
				String name = request.getParameter("name");

				String sql = "select student_number from student where student_number=? and student_name=?";
				PreparedStatement ps = DBTools.getConnection()
						.prepareStatement(sql);
				ps.setString(1, number);
				ps.setString(2, name);
				ResultSet rs = ps.executeQuery();
				if (rs.next()) {
					out.print("yes");
				} else {
					out.print("no");
				}
				out.flush();
				out.close();
				rs.close();
			} else if (parameter.equals("getMajor")) {
				String value = request.getParameter("value");
				String sql = "select * from major where college_name=?";
				PreparedStatement ps = DBTools.getConnection()
						.prepareStatement(sql);
				ps.setString(1, value);
				ResultSet rs = ps.executeQuery();
				while (rs.next()) {
					out.print("<option value=" + rs.getString("major_name")
							+ ">" + rs.getString("major_name") + "</option>");
				}
				out.flush();
				out.close();
				rs.close();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "checkRegister";
	}

	/**
	 * 获取学生信息
	 * 
	 * @return
	 */
	public String getStudentInfo() {
		try {
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();

			String username = (String) session.getAttribute("username");
			if (username == null || username.equals("")) {
				out.print("[{'result':'logout'}]");
			} else {
				String sql = "select * from student where student_number='"
						+ username + "' and isRegisted=1";
				DBTools dbtools = new DBTools();
				ResultSet rs = dbtools.executeQuery(sql);
				if (rs.next()) {
					StringBuffer result = new StringBuffer();
					result.append("[");
					result.append("{");
					result.append("'result':'success'");
					result.append(",'name':'" + rs.getString("student_name")
							+ "'");
					result.append(",'nation':'" + rs.getString("nation") + "'");
					result.append(",'sex':'" + rs.getString("sex") + "'");
					result.append(",'college':'" + rs.getString("college")
							+ "'");
					result.append(",'major':'" + rs.getString("major") + "'");
					result.append(",'politic':'"
							+ rs.getString("political_aff") + "'");
					result.append(",'phone':'" + rs.getString("phone") + "'");
					result.append("}");
					result.append("]");
					out.print(result);
				}
				rs.close();
			}
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "getStudentInfo";
	}

	/**
	 * 获取指定公寓所有可选房间信息
	 * 
	 * @return
	 */
	public String getRoomInfo() {
		try {
			/**
			 * 使用json返回数据
			 */
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();

			String department = request.getParameter("department");
			String floor = request.getParameter("floor");
			if (department == null || department.equals("") || floor == null
					|| floor.equals("")) {
				return null;
			}

			String sql = "select * from room where department=? and floor=?";
			PreparedStatement ps = DBTools.getConnection()
					.prepareStatement(sql);
			ps.setString(1, department);
			ps.setString(2, floor);
			// System.out.println(ps.toString());
			ResultSet rs = ps.executeQuery();
			StringBuffer result = new StringBuffer();
			result.append("[");
			while (rs.next()) {
				result.append("{");
				result.append("'result':'success'");
				result.append(",'room_number':'" + rs.getString("room_number")
						+ "'");
				result.append(",'total':'" + rs.getInt("total") + "'");
				result.append(",'current':'" + rs.getInt("current_number")
						+ "'");
				result.append(",'gender_type':'" + rs.getInt("gender_type")
						+ "'");
				result.append(",'type':'" + rs.getInt("type") + "'");
				result.append(",'chooseAble':'" + rs.getInt("chooseAble") + "'");
				result.append("},");
			}
			rs.close();
			ps.close();
			if(result.charAt(result.length()-1)==','){
				result.deleteCharAt(result.length()-1);			//删除最后一个逗号
			}
			result.append("]");
			out.print(result);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		// return "getRoomInfo";
	}
	
	/**
	 * 获取指定房间号的床位信息
	 * 
	 * @return
	 */
	public String getBedInfo() {
		try {
			/**
			 * 使用json返回数据
			 */
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();

			String roomNumber = request.getParameter("room_number");
			if (roomNumber == null || roomNumber.equals("")) {
				return null;
			}
			int floor = Integer.parseInt(request.getParameter("floor"));

			String sql = "SELECT bed.*, room.* FROM bed"
					+ " LEFT JOIN room ON room.room_number=bed.room_number"
					+ " WHERE bed.room_number=? AND room.floor=?";
			PreparedStatement ps = DBTools.getConnection()
					.prepareStatement(sql);
			ps.setString(1, roomNumber);
			ps.setInt(2, floor);
			// System.out.println(ps.toString());
			ResultSet rs = ps.executeQuery();
			StringBuffer result = new StringBuffer();
			result.append("[");
			while (rs.next()) {
				result.append("{");
				result.append("'result':'success'");
				result.append(",'room_number':'" + rs.getString("room_number")
						+ "'");
				result.append(",'bed_id':'" + rs.getInt("bed_position_id")
						+ "'");
				result.append(",'isChoosen':'" + rs.getInt("isChoosen") + "'");
				result.append(",'opational':'" + rs.getInt("opational") + "'");
				result.append(",'gender_type':'" + rs.getInt("gender_type")
						+ "'");
				result.append(",'type':'" + rs.getInt("type") + "'");
				result.append(",'chooseAble':'" + rs.getInt("chooseAble") + "'");
				result.append(",'total':'" + rs.getInt("total") + "'");
				result.append(",'current':'" + rs.getInt("current_number") + "'");
				result.append("},");
			}
			rs.close();
			ps.close();
			if(result.charAt(result.length()-1)==','){
				result.deleteCharAt(result.length()-1);			//删除最后一个逗号
			}
			result.append("]");
			out.print(result);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		// return "getBedInfo";
	}

	/**
	 * 查询当前学生选择了的房间信息
	 */
	public void getChoosenInfo(){
		try {
			/**
			 * 使用json返回数据
			 */
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();

			String username = (String) session.getAttribute("username");

			if (username == null || username.equals("")) { // 未登录
				out.print("[{'result':'logout'}]");
			} else {
				ResultSet rs = new DBTools()
						.executeQuery("select isChoosen,sex from student where student_number='"
								+ username + "'");
				if (rs.next()) {
					//性别
					if(rs.getString("sex").equals("男")){
						session.setAttribute("gender", 0);
					}else{
						session.setAttribute("gender", 1);
					}
					
					if (rs.getInt("isChoosen") == 1) {		//选择了房间的信息
						String sql = "SELECT * FROM student_room WHERE student_number=?";
						PreparedStatement ps = DBTools.getConnection()
								.prepareStatement(sql);
						// System.out.println(ps.toString());
						ps.setString(1, username);
						ResultSet rs2 = ps.executeQuery();
						StringBuffer result = new StringBuffer();
						result.append("[");
						if (rs2.next()) {
							result.append("{");
							result.append("'result':'true'");
							result.append(",'room_number':'" + rs2.getString("room_number") + "'");
							result.append(",'bed_id':'" + rs2.getInt("bed_position_id") + "'");
							result.append("}");
						}
						rs2.close();
						ps.close();
						result.append("]");
						out.print(result);
						session.setAttribute("isChoosen", "true");
					} else {	//未选择了房间
						out.print("[{'result':'false'}]");
						session.setAttribute("isChoosen", "false");
					}
				} else { // 数据库中没有该学生信息，可能是因为误操作数据库产生。严重！
					out.print("[{'result':'error'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 选择床位
	 * 
	 * @return
	 */
	public String selectBed() {
		try {
			/**
			 * 使用json返回数据
			 */
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();

			String roomNumber = request.getParameter("room_number");
			String bedID = request.getParameter("bed_id");
			String username = (String) session.getAttribute("username");
			String isChoosen = (String)session.getAttribute("isChoosen");

			if (roomNumber == null || roomNumber.equals("") || bedID == null
					|| bedID.equals("")) {
				return null;
			}
			if (username == null || username.equals("")) { // 未登录
				out.print("[{'result':'logout'}]");
			} else {
				//获取当前时间
				java.util.Date dNow = new java.util.Date();
				//设置时间格式
				java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
				String sNow = df.format(dNow);

				String timesql = "select * from timerange where time_start<? and time_end>? and department=?";
				PreparedStatement ps = DBTools.getConnection().prepareStatement(timesql);
				ps.setString(1, sNow);
				ps.setString(2, sNow);
				ps.setString(3, roomNumber.substring(0, 3));
				ResultSet rs = ps.executeQuery();
				if(rs.next()){
					/**
					 * 查询将要选择的床位信息
					 */
					String sql = "SELECT bed.*, room.gender_type,room.total,room.current_number FROM bed"
							+ " LEFT JOIN room ON room.room_number=bed.room_number"
							+ " WHERE bed.room_number=? AND bed.bed_position_id=? AND room.chooseAble=1";
					ps = DBTools.getConnection()
							.prepareStatement(sql);
					ps.setString(1, roomNumber);
					ps.setInt(2, Integer.parseInt(bedID));
					//System.out.println(ps.toString());
					rs = ps.executeQuery();
					if(rs.next()){	//查询到床位信息
						int total = rs.getInt("total");
						int current = rs.getInt("current_number");
						int gender_type = rs.getInt("gender_type");
						int student_gender = -1;
						if(session.getAttribute("gender") != null){
							student_gender=(Integer) session.getAttribute("gender");
						}
						if(gender_type!=student_gender){		//房间的可选性别与该学生性别不符合
							rs.close();
							out.print("[{'result':'genderUnmatched'}]");
							out.flush();
							out.close();
							return null;
						}
						if(rs.getInt("isChoosen")==1){			//该床位已经被选择
							rs.close();
							out.print("[{'result':'bedChoosen'}]");
							out.flush();
							out.close();
							return null;
						}
						if(total == current){		//房间已满
							rs.close();
							out.print("[{'result':'roomFull'}]");
							out.flush();
							out.close();
							return null;
						}
						if (isChoosen!=null && isChoosen.equals("true")) {		//该学生已经选择过床位
							//更改床位选择
							sql = "update student_room set room_number=?,bed_position_id=? where student_number=?";	
							ps = DBTools.getConnection()
									.prepareStatement(sql);
							ps.setString(1, roomNumber);
							ps.setInt(2, Integer.parseInt(bedID));
							ps.setString(3, username);
							// System.out.println(ps.toString());
							/**
							 * 其余表的数据操作通过触发器完成，具体详见数据库结构设计
							 */
							
							if(ps.executeUpdate()>0){
								StringBuffer result = new StringBuffer();
								result.append("[");
								result.append("{");
								result.append("'result':'success'");
								result.append(",'room_number':'" + roomNumber + "'");
								result.append(",'bed_id':'" + bedID + "'");
								result.append("},");
								result.append("]");
								out.print(result);
							}
						} else { // 该学生没有选择床位
							sql = "insert into student_room values(?,?,?)";			//插入学生床位对应表
							
							ps = DBTools.getConnection()
									.prepareStatement(sql);
							ps.setString(1, username);
							ps.setString(2, roomNumber);
							ps.setInt(3, Integer.parseInt(bedID));
							//System.out.println(ps.toString());
							/**
							 * 其余表的数据操作通过触发器完成，具体详见数据库结构设计
							 */
							
							if(ps.executeUpdate()>0){
								StringBuffer result = new StringBuffer();
								result.append("[");
								result.append("{");
								result.append("'result':'success'");
								result.append(",'room_number':'" + roomNumber + "'");
								result.append(",'bed_id':'" + bedID + "'");
								result.append("},");
								result.append("]");
								out.print(result);
							}
						}
					}else{	//查询不到该床位
						out.print("[{'result':'error'}]");
					}
					
				}else{
					out.print("[{'result':'timeerror'}]");
				}
				rs.close();
				ps.close();
			}
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		// return "getBedInfo";
	}
	
	/**
	 * 取消选房
	 */
	public void cancelChoose(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else{
				String sql = "delete from student_room where student_number='"+username+"'";
				/**
				 * 其余表操作通过触发器完成
				 */
				DBTools dbtools = new DBTools();
				if(dbtools.executeUpdate(sql)>0){
					out.print("[{'result':'success'}]");
				}else{
					out.print("[{'result':'error'}]");
				}
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 验证是否可以创建指定账号的管理员账号
	 */
	public void checkAdminUser(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else{
				String sql="select role from admin where id='"+username+"'";
				DBTools db = new DBTools();
				ResultSet rs = db.executeQuery(sql);
				if(rs.next() && rs.getInt("role")==0){
					String newuser = request.getParameter("username");
					sql="select * from admin where id=?";
					PreparedStatement ps = DBTools.getConnection().prepareStatement(sql);
					ps.setString(1, newuser);
					ResultSet rs2 = ps.executeQuery();
					if(rs2.next()){
						out.print("[{'result':'exist'}]");
					}else{
						out.print("[{'result':'yes'}]");
					}
					rs2.close();
					ps.close();
				}else{
					out.print("[{'result':'permission denied'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取管理员列表
	 */
	public void getAdminUser(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else{
				String sql="select role from admin where id='"+username+"'";
				DBTools db = new DBTools();
				ResultSet rs = db.executeQuery(sql);
				if(rs.next() && rs.getInt("role")==0){
					String page = request.getParameter("page");
					sql="SELECT  admin.*,ad.realValue FROM admin"
						+" LEFT JOIN attributeditail AS ad ON attributeid=5 AND delegate=admin.role"
						+" GROUP BY role ORDER BY role ASC LIMIT ?,10";
					PreparedStatement ps = DBTools.getConnection().prepareStatement(sql);
					ps.setInt(1, 10*(Integer.parseInt(page)-1));
					ResultSet rs2 = ps.executeQuery();
					StringBuffer result = new StringBuffer();
					result.append("[");
					while(rs2.next()){
						result.append("{");
						result.append("'result':'success'");
						result.append(",'id':'"+rs2.getString("id")+"'");
						result.append(",'name':'"+rs2.getString("name")+"'");
						String password = rs2.getString("password");
						result.append(",'password':'"+password.substring(0,2)+"***'");
						result.append(",'authority':'"+rs2.getString("realValue")+"'");
						result.append(",'role':"+rs2.getInt("role"));
						result.append("},");
					}
					if(result.charAt(result.length()-1)==','){
						result.deleteCharAt(result.length()-1);			//删除最后一个逗号
					}
					result.append("]");
					out.print(result.toString());
					rs2.close();
					ps.close();
				}else{
					out.print("[{'result':'permission denied'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除指定账号的管理员
	 */
	public void delAdminUser(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else{
				String sql="select role from admin where id='"+username+"'";
				DBTools db = new DBTools();
				ResultSet rs = db.executeQuery(sql);
				if(rs.next() && rs.getInt("role")==0){
					String id = request.getParameter("id");
					sql="DELETE FROM admin WHERE id=?";
					PreparedStatement ps = DBTools.getConnection().prepareStatement(sql);
					ps.setString(1, id);
					boolean result = ps.executeUpdate()>0;
					if(result){
						out.print("[{'result':'success'}]");
					}else{
						out.print("[{'result':'failed'}]");
					}
					ps.close();
				}else{
					out.print("[{'result':'permission denied'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 管理员获取用户控制菜单
	 */
	public void getUserNav(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else{
				String sql="select role from admin where id='"+username+"'";
				DBTools db = new DBTools();
				ResultSet rs = db.executeQuery(sql);
				if(rs.next()){
					if(rs.getInt("role")==0){
						StringBuffer result = new StringBuffer();
						result.append("[");
						result.append("{'result':'success','url':'addAdmin.html','name':'新增用户'}");
						result.append(",{'result':'success','url':'showAdmin.html','name':'查看用户'}");
						result.append(",{'result':'success','url':'resetPass.html','name':'密码修改'}");
						result.append("]");
						out.print(result.toString());
					}else{
						out.print("[{'result':'success','url':'resetPass.html','name':'密码修改'}]");
					}
				}else{
					out.print("[{'result':'error'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 管理员获取公寓管理控制菜单
	 */
	public void getDepNav(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else{
				String sql="select role from admin where id='"+username+"'";
				DBTools db = new DBTools();
				ResultSet rs = db.executeQuery(sql);
				if(rs.next()){
					if(rs.getInt("role")==0){
						StringBuffer result = new StringBuffer();
						result.append("[");
						result.append("{'result':'success','url':'A10_control.html','name':'A10公寓管理'}");
						result.append(",{'result':'success','url':'A17_control.html','name':'A17公寓管理'}");
						result.append(",{'result':'success','url':'B04_control.html','name':'B04公寓管理'}");
						result.append(",{'result':'success','url':'B06_control.html','name':'B06公寓管理'}");
						result.append("]");
						out.print(result.toString());
					}else if(rs.getInt("role")==1){
						out.print("[{'result':'success','url':'A10_control.html','name':'A10公寓管理'}]");
					}else if(rs.getInt("role")==2){
						out.print("[{'result':'success','url':'A17_control.html','name':'A17公寓管理'}]");
					}else if(rs.getInt("role")==3){
						out.print("[{'result':'success','url':'B04_control.html','name':'B04公寓管理'}]");
					}else if(rs.getInt("role")==4){
						out.print("[{'result':'success','url':'B06_control.html','name':'B06公寓管理'}]");
					}
				}else{
					out.print("[{'result':'error'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 以管理员身份获取指定床位的学生信息
	 */
	public void getChoosenInfoByAdmin(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			String identify = (String)session.getAttribute("identify");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else if(!identify.equals("admin")){
				out.print("[{'result':'permission denied'}]");
			}else{
				String sql="select role from admin where id='"+username+"'";
				DBTools db = new DBTools();
				ResultSet rs = db.executeQuery(sql);
				if(rs.next()){
					boolean permission =false;
					String room = request.getParameter("room");
					String bed = request.getParameter("bed");
					String department = room.substring(0,3);
					int role = rs.getInt("role");
					if(role==0){
						permission = true;
					}else{
						sql = "select realValue from attributeditail where attributeid=5 and delegate='"+role+"'";
						rs = db.executeQuery(sql);
						rs.next();
						String dep_real = rs.getString("realValue");
						if(department.equals(dep_real.substring(0, 3))){
							permission = true;
						}else{
							permission = false;
						}
					}
					if(permission){
						sql="select student_number from student_room where room_number=? and bed_position_id=?";
						PreparedStatement ps = DBTools.getConnection().prepareStatement(sql);
						ps.setString(1, room);
						ps.setString(2, bed);
						ResultSet rs2 = ps.executeQuery();
						if(rs2.next()){
							out.print("[{'result':'choosed','student':'"+rs2.getString("student_number")+"'}]");
						}else{
							out.print("[{'result':'unchoosed'}]");
						}
						rs2.close();
						ps.close();
					}else{
						out.print("[{'result':'permission denied'}]");
					}
				}else{
					out.print("[{'result':'error'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 管理员获取统计信息控制菜单
	 */
	public void getRoomNav(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else{
				String sql="select role from admin where id='"+username+"'";
				DBTools db = new DBTools();
				ResultSet rs = db.executeQuery(sql);
				if(rs.next()){
					out.print("[{'result':'success','url':'chooseStatistics.html','name':'选房统计'}");
					out.print(",{'result':'success','url':'leftStatistics.html','name':'空床统计'}");
					if(rs.getInt("role")==0){
						out.print(",{'result':'success','url':'studentStatistics.html','name':'学生信息统计'}]");
					}else{
						out.print("]");
					}
				}else{
					out.print("[{'result':'error'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 设置房间信息
	 */
	public void setRoomInfo(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			String identify = (String)session.getAttribute("identify");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else if(!identify.equals("admin")){
				out.print("[{'result':'permission denied'}]");
			}else{
				String sql="select role from admin where id='"+username+"'";
				DBTools db = new DBTools();
				ResultSet rs = db.executeQuery(sql);
				if(rs.next()){
					boolean permission =false;
					String room = request.getParameter("room");
					String department = room.substring(0,3);
					int role = rs.getInt("role");
					if(role==0){
						permission = true;
					}else{
						sql = "select realValue from attributeditail where attributeid=5 and delegate='"+role+"'";
						rs = db.executeQuery(sql);
						rs.next();
						String dep_real = rs.getString("realValue");
						if(department.equals(dep_real.substring(0, 3))){
							permission = true;
						}else{
							permission = false;
						}
					}
					if(permission){
						int chooseAble = Integer.parseInt(request.getParameter("state"));
						int genderType = Integer.parseInt(request.getParameter("sex"));
						int total = Integer.parseInt(request.getParameter("total"));
						int floor = Integer.parseInt(request.getParameter("floor"));
						String operation = request.getParameter("operation");
						if(operation!=null && operation.equals("modify")){
							sql = "update room set total=?,gender_type=?,chooseAble=?,type=? where room_number=?";
							PreparedStatement ps = DBTools.getConnection().prepareStatement(sql);
							/**
							 * 对参数为空没有进行判断，下同
							 */
							ps.setInt(1, total);
							ps.setInt(2, genderType);
							ps.setInt(3, chooseAble);
							ps.setInt(4, total);
							ps.setString(5, room);
							//System.out.println(ps.toString());
							boolean result = ps.executeUpdate()>0;
							if(result){
								out.print("[{'result':'success'}]");
							}else{
								out.print("[{'result':'failed'}]");
							}
							ps.close();
						}else{
							sql="insert into room values(?,?,?,?,0,?,?,?)";
							PreparedStatement ps = DBTools.getConnection().prepareStatement(sql);
							/**
							 * 对参数为空没有进行判断，下同
							 */
							ps.setString(1, room);
							ps.setString(2, department);
							ps.setInt(3, floor);
							ps.setInt(4, total);
							ps.setInt(5, genderType);
							ps.setInt(6, total);
							ps.setInt(7, chooseAble);
							boolean result = ps.executeUpdate()>0;
							if(result){
								out.print("[{'result':'success'}]");
							}else{
								out.print("[{'result':'failed'}]");
							}
							ps.close();	
						}
					}else{
						out.print("[{'result':'permission denied'}]");
					}
				}else{
					out.print("[{'result':'error'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 统计学生选房信息
	 */
	public void getStudentRoomInfo(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			String identify = (String)session.getAttribute("identify");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else if(!identify.equals("admin")){
				out.print("[{'result':'permission denied'}]");
			}else{
				String sql="select role from admin where id='"+username+"'";
				DBTools db = new DBTools();
				ResultSet rs = db.executeQuery(sql);
				if(rs.next()){
					boolean permission =false;
					String addSql="";
					int role = rs.getInt("role");
					if(role==0){
						permission = true;
					}else{
						sql = "select realValue from attributeditail where attributeid=5 and delegate='"+role+"'";
						rs = db.executeQuery(sql);
						
						if(rs.next()){
							String dep_real = rs.getString("realValue");
							permission = true;
							addSql=" WHERE room.department='"+dep_real.substring(0, 3)+"'";
						}
					}
					
					if(permission){
						sql = "SELECT student_room.*,room.department,room.floor FROM student_room"
							+" LEFT JOIN room ON room.room_number=student_room.room_number"+addSql;
						rs = db.executeQuery(sql);
						StringBuffer result = new StringBuffer();
						result.append("[{'result':'success'},");
						result.append("{'aaData':[");
						while(rs.next()){
							result.append("[");
							result.append("'"+rs.getString("student_number")+"'");
							result.append(",'"+rs.getString("room_number")+"'");
							result.append(",'"+rs.getString("bed_position_id")+"'");
							result.append(",'"+rs.getString("floor")+"'");
							result.append(",'"+rs.getString("department")+"'");
							result.append("],");
						}
						if(result.charAt(result.length()-1)==','){
							result.deleteCharAt(result.length()-1);			//删除最后一个逗号
						}
						result.append("]}]");
						out.print(result.toString());	
					}else{
						out.print("[{'result':'permission denied'}]");
					}
				}else{
					out.print("[{'result':'error'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 统计剩余床位信息
	 */
	public void getLeftBedInfo(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			String identify = (String)session.getAttribute("identify");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else if(!identify.equals("admin")){
				out.print("[{'result':'permission denied'}]");
			}else{
				String sql="select role from admin where id='"+username+"'";
				DBTools db = new DBTools();
				ResultSet rs = db.executeQuery(sql);
				if(rs.next()){
					boolean permission =false;
					String addSql="";
					int role = rs.getInt("role");
					if(role==0){
						permission = true;
					}else{
						sql = "select realValue from attributeditail where attributeid=5 and delegate='"+role+"'";
						rs = db.executeQuery(sql);
						
						if(rs.next()){
							String dep_real = rs.getString("realValue");
							permission = true;
							addSql=" AND room.department='"+dep_real.substring(0, 3)+"'";
						}
					}			
					/*if(rs.getInt("role")==0){
						permission = true;
					}else if(rs.getInt("role")==1){
						permission = true;
						addSql=" AND room.department='A10'";
					}else if(rs.getInt("role")==2){
						permission = true;
						addSql=" AND room.department='A17'";
					}*/
					if(permission){
						sql = "SELECT bed.room_number,bed.bed_position_id,room.floor,room.department FROM bed"
							+" LEFT JOIN room ON room.room_number=bed.room_number"
							+" WHERE bed.isChoosen=0"+addSql;
						rs = db.executeQuery(sql);
						StringBuffer result = new StringBuffer();
						result.append("[{'result':'success'},");
						result.append("{'aaData':[");
						while(rs.next()){
							result.append("[");
							result.append("'"+rs.getString("room_number")+"'");
							result.append(",'"+rs.getString("bed_position_id")+"'");
							result.append(",'"+rs.getString("floor")+"'");
							result.append(",'"+rs.getString("department")+"'");
							result.append("],");
						}
						result.deleteCharAt(result.length()-1);			//删除最后一个逗号
						result.append("]}]");
						out.print(result.toString());	
					}else{
						out.print("[{'result':'permission denied'}]");
					}
				}else{
					out.print("[{'result':'error'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 管理员统计学生信息
	 */
	public void getStudentStatistics(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			String identify = (String)session.getAttribute("identify");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else if(!identify.equals("admin")){
				out.print("[{'result':'permission denied'}]");
			}else{
				String sql="select role from admin where id='"+username+"'";
				DBTools db = new DBTools();
				ResultSet rs = db.executeQuery(sql);
				if(rs.next()){
					if(rs.getInt("role")==0){
						sql = "SELECT * FROM student LEFT JOIN student_room on student_room.student_number=student.student_number WHERE isRegisted=1 ";
						rs = db.executeQuery(sql);
						
						StringBuffer result = new StringBuffer();
						result.append("[{'result':'success'},");
						result.append("{'aaData':[");
						while(rs.next()){
							result.append("[");
							result.append("'"+rs.getString("student_number")+"'");
							result.append(",'"+rs.getString("student_name")+"'");
							result.append(",'"+rs.getString("nation")+"'");
							result.append(",'"+rs.getString("sex")+"'");
							result.append(",'"+rs.getString("college")+"'");
							result.append(",'"+rs.getString("major")+"'");
							result.append(",'"+rs.getString("political_aff")+"'");
							result.append(",'"+rs.getString("phone")+"'");
							
							String department="无";
							String room="无";
							String bed="无";
							room=rs.getString("room_number");
							if(room==null || room.equals(""))room="无";
							else{ 
								department=room.substring(0, 3);
								bed=rs.getString("bed_position_id");
							}
							result.append(",'"+department+"'");
							result.append(",'"+room+"'");
							result.append(",'"+bed+"'");
							result.append("],");
						}
						if(result.charAt(result.length()-1)==','){
							result.deleteCharAt(result.length()-1);			//删除最后一个逗号
						}
						result.append("]}]");
						out.print(result.toString());	
					}else{
						out.print("[{'result':'permission denied'}]");
					}
				}else{
					out.print("[{'result':'error'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取公寓可选时间
	 */
	public void getTimeRange(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String department = request.getParameter("department");
			String sql = "select * from timerange where department=?";
			PreparedStatement ps = DBTools.getConnection().prepareStatement(sql);
			/**
			 * 对参数为空没有进行判断，下同
			 */
			ps.setString(1, department);
			// System.out.println(ps.toString());
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				out.print("[{'result':'success'}");
				out.print(",{'opentime':'"+rs.getDate("time_start")+"'");
				out.print(",'closetime':'"+rs.getDate("time_end")+"'");
				out.print("}]");
			} else {
				out.print("[{'result':'failed'}]");
			}
			rs.close();
			ps.close();
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 设置公寓可选时间
	 */
	public void setTimeRange(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			String identify = (String)session.getAttribute("identify");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else if(!identify.equals("admin")){
				out.print("[{'result':'permission denied'}]");
			}else{
				String sql="select role from admin where id='"+username+"'";
				DBTools db = new DBTools();
				ResultSet rs = db.executeQuery(sql);
				if(rs.next()){
					boolean permission =false;
					String department = request.getParameter("department");
					int role = rs.getInt("role");
					if(role==0){
						permission = true;
					}else{					//查询字典判断权限
						sql = "select realValue from attributeditail where attributeid=5 and delegate='"+role+"'";
						rs = db.executeQuery(sql);
						rs.next();
						String dep_real = rs.getString("realValue");
						if(department.equals(dep_real.substring(0, 3))){
							permission = true;
						}else{
							permission = false;
						}
					}
					/*if(rs.getInt("role")==0){
						permission = true;
					}else if(rs.getInt("role")==1){
						if(department.equals("A10")){
							permission = true;
						}else{
							permission = false;
						}
					}else if(rs.getInt("role")==2){
						if(department.equals("A17")){
							permission = true;
						}else{
							permission = false;
						}
					}*/
					if(permission){
						sql = "update timerange set time_start=?,time_end=? where department=?";
						PreparedStatement ps = DBTools.getConnection().prepareStatement(sql);
						/**
						 * 对参数为空没有进行判断，下同
						 */
						ps.setString(1, request.getParameter("opentime"));
						ps.setString(2, request.getParameter("closetime"));
						ps.setString(3, department);
						// System.out.println(ps.toString());
						boolean result = ps.executeUpdate() > 0;
						if (result) {
							out.print("[{'result':'success'}]");
						} else {
							out.print("[{'result':'failed'}]");
						}
						ps.close();

					}else{
						out.print("[{'result':'permission denied'}]");
					}
				}else{
					out.print("[{'result':'error'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 更换房间状态
	 */
	/*
	public void changeRoomState(){
		try{
			response.setContentType("text/json");
			response.setCharacterEncoding("utf-8");
			session.getServletContext();
			PrintWriter out = response.getWriter();
			String username = (String)session.getAttribute("username");
			String identify = (String)session.getAttribute("identify");
			if(username==null || username.length()<0){
				out.print("[{'result':'logout'}]");
			}else if(!identify.equals("admin")){
				out.print("[{'result':'permission denied'}]");
			}else{
				String sql="select role from admin where id='"+username+"'";
				DBTools db = new DBTools();
				ResultSet rs = db.executeQuery(sql);
				if(rs.next()){
					if(rs.getInt("role")==0){
						String room = request.getParameter("room");
						String chooseAble = request.getParameter("chooseAble");
						sql="update room set chooseAble=? where room_number=?";
						PreparedStatement ps = DBTools.getConnection().prepareStatement(sql);
						*//**
						 * 对参数为空没有进行判断，下同
						 *//*
						ps.setInt(1, Integer.parseInt(chooseAble));
						ps.setString(2, room);
						boolean result = ps.executeUpdate()>0;
						if(result){
							out.print("[{'result':'success'}]");
						}else{
							out.print("[{'result':'failed'}]");
						}
						ps.close();
					}else if(rs.getInt("role")==1){
						String room = request.getParameter("room");
						String department = room.substring(0, 3);
						if(department.equals("A10")){
							String chooseAble = request.getParameter("chooseAble");
							sql="update room set chooseAble=? where room_number=?";
							PreparedStatement ps = DBTools.getConnection().prepareStatement(sql);
							ps.setInt(1, Integer.parseInt(chooseAble));
							ps.setString(2, room);
							boolean result = ps.executeUpdate()>0;
							if(result){
								out.print("[{'result':'success'}]");
							}else{
								out.print("[{'result':'failed'}]");
							}
							ps.close();
						}else{
							out.print("[{'result':'permission denied'}]");
						}
					}else if(rs.getInt("role")==2){
						String room = request.getParameter("room");
						String department = room.substring(0, 3);
						if(department.equals("A17")){
							String chooseAble = request.getParameter("chooseAble");
							sql="update room set chooseAble=? where room_number=?";
							PreparedStatement ps = DBTools.getConnection().prepareStatement(sql);
							ps.setInt(1, Integer.parseInt(chooseAble));
							ps.setString(2, room);
							boolean result = ps.executeUpdate()>0;
							if(result){
								out.print("[{'result':'success'}]");
							}else{
								out.print("[{'result':'failed'}]");
							}
							ps.close();
						}else{
							out.print("[{'result':'permission denied'}]");
						}
					}
				}else{
					out.print("[{'result':'error'}]");
				}
				rs.close();
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	*/
}
